package com.hobobe.tiercel.server.filter;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelDownstreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hobobe.tiercel.XLCharSetFactory;
import com.hobobe.tiercel.server.handler.TcpResponse;

public class ServerEncoder extends SimpleChannelDownstreamHandler {
	private static final Logger logger = LoggerFactory.getLogger(ServerEncoder.class);

	@Override
	public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {

		TcpResponse response = (TcpResponse) e.getMessage();
		ByteBuffer headBuffer = ByteBuffer.allocate(16);
		/**
		 * 先组织报文头
		 */
		headBuffer.put(response.getEncode());
		headBuffer.put(response.getEncrypt());
		headBuffer.put(response.getCompress());
		headBuffer.put(response.getExtend1());
		headBuffer.put(response.getExtend2());
		headBuffer.putInt(response.getSessionid());
		headBuffer.putInt(response.getResult());

		/**
		 * 组织报文的数据部分
		 */
		ChannelBuffer dataBuffer = encode(response.getEncode(),response.getData());
		int length = dataBuffer.readableBytes();
		headBuffer.putInt(length);
		/**
		 * 非常重要 ByteBuffer需要手动flip()，ChannelBuffer不需要
		 */
		headBuffer.flip();
		ChannelBuffer totalBuffer = ChannelBuffers.dynamicBuffer();
		totalBuffer.writeBytes(headBuffer);
		logger.info("totalBuffer size=" + totalBuffer.readableBytes());
		totalBuffer.writeBytes(dataBuffer);
		logger.info("totalBuffer size=" + totalBuffer.readableBytes());
		Channels.write(ctx, e.getFuture(), totalBuffer);
	}
	
	 /**
     * 编码报文的数据部分
     * @param encode
     * @param values
     * @return
     */
    public ChannelBuffer encode(int encode,byte[] data){
        ChannelBuffer totalBuffer=null;
        if (data!=null && data.length>0) {
           totalBuffer=ChannelBuffers.dynamicBuffer();
            int length=0,index=0;
            ChannelBuffer [] channelBuffers=new ChannelBuffer[1];
            Charset charset=XLCharSetFactory.getCharset(encode);
          
              
                ChannelBuffer buffer=ChannelBuffers.dynamicBuffer();
                buffer.writeInt(data.length);
                buffer.writeBytes(data);
                
                channelBuffers[0]=buffer;
                length+=buffer.readableBytes();
            
            for (int i = 0; i < channelBuffers.length; i++) {
                totalBuffer.writeBytes(channelBuffers[i]);
            }
        }
        return totalBuffer;
    }
	
	
}
